package cn.wolfcode.trip.base.service.impl;

import cn.wolfcode.trip.base.domain.Integral;
import cn.wolfcode.trip.base.domain.Signin;
import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.mapper.IntegralMapper;
import cn.wolfcode.trip.base.mapper.SigninMapper;
import cn.wolfcode.trip.base.service.ISigninService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SigninServiceImpl implements ISigninService {
    @Autowired
    private SigninMapper signinMapper;
    @Autowired
    private IntegralMapper integralMapper;
    @Override
    public void save(Signin signin) {
        //查询该用户今天是否签到
        List<Signin> today = signinMapper.queryToday(signin.getUserId());
        //如果没有才可以新增签到数据
        if (today.size() == 0){
            Date date = new Date();
            //查询该用户昨天是否签到
            List<Signin> yesterday = signinMapper.queryYesterday(signin.getUserId());
            if (yesterday.size() == 0){
                //如果昨天的数据为null,则将连续签到天数设置为1
                signin.setDays(1);
            }else {
                //否则,查出昨天签到的数据,获取连续签到天数,并加1
                Signin yesterSignin = yesterday.get(0);
                signin.setDays(yesterSignin.getDays()+1);
            }
            try{
                //签到成功就保存到数据库
                signinMapper.insert(signin);
                //并且增加1积分
                Integral integral = new Integral();
                integral.setState(true);
                User u = new User();
                u.setId(signin.getUserId());
                integral.setChangeMoney(1);
                integral.setUser(u);
                integral.setUpdateTime(signin.getTime());
                integralMapper.insert(integral);
            }catch (Exception e){
                e.printStackTrace();
            }
        }else {
            throw new RuntimeException("一天只能签一次呢(。・・)ノ");
        }
    }

    @Override
    public boolean getToday(Long userId) {
        List<Signin> list = signinMapper.queryToday(userId);
        if(list.size()!=0){
            return true;
        }else{
            return false;
        }
    }

    @Override
    public List<Signin> getHistory(Long userId) {
        return signinMapper.getHistory(userId);
    }

    @Override
    public Integer getHistoryDays(Long userId) {
        return signinMapper.getHistoryDays(userId);
    }
}
